package com.example.smartagriculture.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagriculture.controller.DTO.LoginDTO;
import com.example.smartagriculture.controller.DTO.RePwdDTO;
import com.example.smartagriculture.controller.DTO.UserDTO;
import com.example.smartagriculture.entity.Account;
import com.example.smartagriculture.mapper.AccountMapper;
import com.example.smartagriculture.service.IAccountService;
import com.example.smartagriculture.utils.MailUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {
    //redisTemplate管理redis
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private AccountMapper accountMapper;
    //登录（进行密码和账号的验证）
    @Override
    public Account Login(LoginDTO loginDTO) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Account::getAccountNo, loginDTO.getAccountNo())
                .eq(Account::getPassword, loginDTO.getAccountPassword());
        return this.getOne(queryWrapper);
    }

    //获取验证码
    @Override
    public String getCode() {

        String[] codeChars = {
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
                "U", "V", "W", "X", "Y", "Z"
        };

        StringBuilder code = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(codeChars.length);
            code.append(codeChars[index]);
        }
        Long t = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(t);
        //将键（时间戳）值（随机验证码）对放进redis容器
        redisTemplate.opsForValue().set(s, code);
//        规定验证码失效时间
        redisTemplate.expire(s, 20, TimeUnit.MINUTES);
        System.out.println(code);
        return code.toString();
    }


    @Override
    public Boolean mailCode(RePwdDTO rePwdDTO) {
        Account account = null;
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        if (rePwdDTO.getType().equals("type2")) {
            queryWrapper.lambda().eq(Account::getMail, rePwdDTO.getMail());
        } else if (rePwdDTO.getType().equals("type1")){
            queryWrapper.lambda().eq(Account::getAccountNo, rePwdDTO.getAccountNo()).eq(Account::getMail, rePwdDTO.getMail());
        }else if (rePwdDTO.getType().equals("type3")){
            queryWrapper.lambda().eq(Account::getMail , rePwdDTO.getMail());
            account=this.getOne(queryWrapper);
            if(account!=null){
                return false;
            }
            Thread thread = new Thread(() -> sendMail(rePwdDTO.getMail()));
            thread.start();
            return true;
        }
        account = this.getOne(queryWrapper);
        if (account != null) {
            //被注释的内容是实现异步的另一种方式（哭）
//            ExecutorService executorService = Executors.newSingleThreadExecutor();
            Thread thread = new Thread(() -> sendMail(rePwdDTO.getMail()));
            thread.start();
//            CompletableFuture.runAsync(()->{

//            },executorService);
//            executorService.shutdown();
//            发送邮件
            return true;
        }
        return false;
    }

    @Override
    public Boolean rePwd(RePwdDTO rePwdDTO) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Account::getAccountNo, rePwdDTO.getAccountNo());
        Account account = this.getOne(queryWrapper);
        account.setPassword(rePwdDTO.getNewPassword());
        return this.updateById(account);
    }

    @Override
    public Boolean verifyCode(RePwdDTO rePwdDTO) {
        return rePwdDTO.getCode().equals(redisTemplate.opsForValue().get(rePwdDTO.getMail()));
    }

    @Override
    public Boolean signup(RePwdDTO rePwdDTO) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Account::getAccountNo, rePwdDTO.getAccountNo());
        if (this.getOne(queryWrapper) != null) {
            return false;
        }else {
            Account account = new Account();
            account.setAccountNo(rePwdDTO.getAccountNo());
            account.setMail(rePwdDTO.getMail());
            account.setPassword(rePwdDTO.getPassword());
            return this.save(account);
        }
    }

    @Override
    public List<UserDTO> selectAll() {
        return accountMapper.selectAll();
    }

    public void sendMail(String mail) {
        String code = getCode();
        //此处把键值改为目标用户的邮箱
        redisTemplate.opsForValue().set(mail, code);
        //设置时间
        redisTemplate.expire(mail, 5, TimeUnit.MINUTES);
        Set<String> set = new HashSet<>();
        set.add(mail);
        MailUtil.sendEmail(set, "有一个智慧农业系统需要您的验证",
                "您的验证码为：" + code + "请在20分钟内进行验证！\n如果您对此验证不知情请注意您的账号安全！");
    }


}
